package org.xx.armory.commons;

import java.io.IOException;
import java.io.InputStream;
import java.nio.ByteBuffer;

import static org.xx.armory.commons.Validators.rejectIfNull;

public class ByteBufferInputStream
        extends InputStream {
    private final ByteBuffer buffer;

    public ByteBufferInputStream(
            ByteBuffer buffer
    ) {
        this(buffer, true);
    }

    public ByteBufferInputStream(
            ByteBuffer buffer,
            boolean rewind
    ) {
        this.buffer = rejectIfNull(buffer, "buffer");
        if (rewind) {
            this.buffer.rewind();
        }
    }

    @Override
    public int read()
            throws IOException {
        if (this.buffer.hasRemaining()) {
            return this.buffer.get();
        } else {
            return -1;
        }
    }
}
